﻿using Microsoft.Extensions.Caching.Memory;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using System.Collections.Concurrent;
using System.Threading.Tasks;
using Volo.Abp.DependencyInjection;

namespace Xms.Abp.Caching;

public class MemoryCacheProvider : CacheProviderBase, ITransientDependency
{
    public override string Name => "Default";

    public MemoryCacheProvider(IAbpLazyServiceProvider lazyServiceProvider)
        : base(lazyServiceProvider)
    {
    }

    protected override Task<string> GetConnectionStringAsync()
    {
        return Task.FromResult("Memory");
    }

    protected override IXmsCache GetOrAddCache(ConcurrentDictionary<string, IXmsCache> caches, string connectionString)
    {
        return GetOrAddCache(LazyServiceProvider, caches, connectionString);
    }

    internal static IXmsCache GetOrAddCache(IAbpLazyServiceProvider lazyServiceProvider, ConcurrentDictionary<string, IXmsCache> caches, string connectionString)
    {
        return caches.GetOrAdd(connectionString, s => CreateCache(lazyServiceProvider));
    }

    internal static IXmsCache CreateCache(IAbpLazyServiceProvider lazyServiceProvider)
    {
        var options = lazyServiceProvider.LazyGetRequiredService<IOptions<MemoryDistributedCacheOptions>>();
        return new XmsMemoryCache(options, lazyServiceProvider.LazyGetRequiredService<ILoggerFactory>());
    }
}

public class MemoryCacheProvider<TCacheContext> : CacheProviderBase<TCacheContext>, ICacheProvider<TCacheContext>
    where TCacheContext : CacheContext<TCacheContext>
{
    public override string Name => "Default";

    public MemoryCacheProvider(IAbpLazyServiceProvider lazyServiceProvider)
        : base(lazyServiceProvider)
    {
    }

    protected override Task<string> GetConnectionStringAsync()
    {
        return Task.FromResult("Memory");
    }

    protected override IXmsCache GetOrAddCache(ConcurrentDictionary<string, IXmsCache> caches, string connectionString)
    {
        return MemoryCacheProvider.GetOrAddCache(LazyServiceProvider, caches, connectionString);
    }
}
